package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author biu
 * @since 2025-03-13
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.getTopSale();

    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {

         return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        //查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, skuId);
        queryWrapper.select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);

        //组装商品价格对象
        /*ProductSku productSku = baseMapper.selectById(skuId);*/
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());

        return skuPriceVo;
    }

    public Map<String, Long> getSkuSpecValue(Long productId) {

        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, productId);
        queryWrapper.select(ProductSku::getSkuSpec, ProductSku::getId);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        Map<String, Long> skuSpecValueMap = productSkuList.stream().collect(
                Collectors.toMap(
                        ProductSku::getSkuSpec,
                        ProductSku::getId
                )
        );

        return skuSpecValueMap;
    }

    @Override
    public ProductSku getProductSku(Long skuId) {
        //从redis中获取sku信息
        String dataKey = "product:sku:" + skuId;
        /*String redisJson = redisTemplate.opsForValue().get(dataKey);
        ProductSku productSku = JSONObject.parseObject(redisJson, ProductSku.class);*/
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
        //如果有则直接返回
        if(productSku != null){
            return productSku;
        }

        log.info("加分布式锁。。。。。。");
        //如果没有则查询数据库
        //加分布式锁
        String lockKey = "product:sku:lock:" + skuId;
        String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
        if(flag){

            log.info("获取到分布式锁");

            try {
                //再次从redis中获取信息
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                //如果有则直接返回
                if(productSku != null){
                    return productSku;
                }

                //如果没有查询数据库中数据
                log.info("进入数据库查询。。。。。。");
                productSku = baseMapper.selectById(skuId);
                long ttl = 60;
                if(productSku == null){
                    productSku = new ProductSku();
                    ttl = 30;
                }

                //将查询到的数据放入redis缓存
            /*String json = JSONObject.toJSONString(productSku);
            redisTemplate.opsForValue().set(dataKey, json);*/
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);

                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放分布式锁
                //lua脚本
                String script = """
                        if redis.call('get', KEYS[1]) == ARGV[1] then
                            return redis.call('del', KEYS[1])
                        else
                            return 0
                        end
                        """;

                //释放锁
                Boolean lock = (Boolean)redisTemplate.execute(
                        new DefaultRedisScript<Boolean>(script, Boolean.class),
                        Arrays.asList(lockKey),
                        lockValue);
                System.out.println("锁释放成功：" + lock);
            }
        }else{

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return getProductSku(skuId);
        }
    }


    //查找最新价格的方法
    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId, skuIdList);
        queryWrapper.select(ProductSku::getId, ProductSku::getSalePrice);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        if(!CollectionUtils.isEmpty(productSkuList)){
            List<SkuPriceVo> skuPriceVoList = productSkuList.stream().map(productSku -> {
                SkuPriceVo skuPriceVo = new SkuPriceVo();
                skuPriceVo.setSkuId(productSku.getId());
                skuPriceVo.setSalePrice(productSku.getSalePrice());
                return skuPriceVo;
            }).toList();

            return skuPriceVoList;
        }
        return null;
    }

}
